package com.atguigu.gmall.list.Service.impl;

import com.atguigu.gmall.list.Service.SearchService;

import com.atguigu.gmall.list.repository.GoodsRepository;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.list.SearchAttr;
import com.atguigu.gmall.model.product.BaseAttrInfo;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    //服务层调用客户端
    //自定义数据接口
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void upperGoods(Long skuId) {
        Goods goods = new Goods();
        SkuInfo skuInfo = productFeignClient.skuInfo(skuId);
        if (skuInfo != null) {

            goods.setId(skuId);
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setTitle(skuInfo.getSkuName());
            goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setCreateTime(new Date());
            //赋值品牌数据
            BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
            goods.setTmId(skuInfo.getTmId());
            goods.setTmName(trademark.getTmName());
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
            //流式编程
            List<SearchAttr> searchAttrList = attrList.stream().map(baseAttrInfo -> {
                SearchAttr searchAttr = new SearchAttr();
                searchAttr.setAttrId(baseAttrInfo.getId());
                return searchAttr;
            }).collect(Collectors.toList());

            goods.setAttrs(searchAttrList);

        }


        goodsRepository.save(goods);

    }

    @Override
    public void lowerGoods(Long skuId) {
        goodsRepository.deleteById(skuId);

    }

    //使用redis先考虑数据类型，再考虑key
    @Override
    public void incrHotScore(Long skuId) {
        String hotScore = "hotScore";
        Double count = redisTemplate.opsForZSet().incrementScore(hotScore, "SkuId" + skuId, 1);
        if (count % 10 == 0) {
            Optional<Goods> optional = goodsRepository.findById(skuId);
            Goods goods = optional.get();
            goods.setHotScore(count.longValue());
            goodsRepository.save(goods);
        }

    }
}
